import { _decorator, resources, Prefab, Button, SpriteFrame, Node, Sprite, Asset, AudioClip } from 'cc';
import Singleton from '../base/Singleton';

export class ResourceMgr extends Singleton {

    static get Instance() {
        return super.GetInstance<ResourceMgr>()
    }

    /**
     * 增加按钮事件
     * @param curNode 
     * @param caller 
     * @param func 
     * @returns 
     */
    addButtonListen(curNode: Node, caller: any, func: Function) {
        const button = curNode.getComponent(Button)
        if (!button) {
            return;
        }
        curNode.on('click', func, caller)
    }

    /**
     * Sprite设置SpriteFrame
     * @param node 
     * @param path 
     * @returns 
     */
    addSprite(node: Node, path: string): Promise<any> {
        return new Promise((resolve, reject) => {
            resources.load(path + "/spriteFrame", SpriteFrame, (err, spriteFrame: SpriteFrame) => {
                if (err) {
                    reject(err)
                    return;
                }
                node.getComponent(Sprite).spriteFrame = spriteFrame
                resolve(1)
            })
        })
    }


    /**
    * 加载资源文件夹
    * @param path 
    * @returns 
    */
    loadDir<T extends Asset>(path: string): Promise<T[]> {
        return new Promise((resolve, reject) => {
            resources.loadDir<T>(path, (err, resource: T[]) => {
                if (err) {
                    reject(err)
                    return;
                }
                resolve(resource)
            })
        })
    }

    /**
     * 加载预制体
     * @param prefabPath 
     * @returns 
     */
    loadPrefab(prefabPath: string): Promise<Prefab> {
        return new Promise((resolve, reject) => {
            resources.load(prefabPath, Prefab, (err, prefab) => {
                if (err) {
                    reject(err)
                    return;
                }
                resolve(prefab)
            })
        })
    }

    /**
     * 加载音乐或音效
     * @param path 
     * @returns 
     */
    loadAudio(path: string): Promise<AudioClip> {
        return new Promise((resolve, reject) => {
            resources.load(path, AudioClip, (err: Error, resource: AudioClip) => {
                if (err) {
                    reject(err)
                    return;
                }
                resolve(resource);
            })
        })
    }

}
